<template>
  <div class="app-container">
    <div class="container-bg">
      <div class="filter-container m-margin-b15">
        <el-button type="primary" @click="addUser">添加用户</el-button>
        <el-button icon="el-icon-refresh" type="primary" plain @click="getList"
        >刷新
        </el-button>
      </div>
      <el-table
        :data="list"
        border
        element-loading-text="Loading"
        fit
        highlight-current-row
        v-loading="tableLoading"
      >
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <!-- <el-table-column align="center" label="序号" width="120">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column> -->
        <el-table-column align="center" label="用户名">
          <template slot-scope="scope">{{ scope.row.sUserName }}</template>
        </el-table-column>
        <el-table-column align="center" label="用户类型">
          <template slot-scope="scope">
            <div v-if="scope.row.iUserLevel == '0'">超级管理员</div>
            <div v-if="scope.row.iUserLevel == '1'">管理员</div>
            <div v-if="scope.row.iUserLevel == '2'">普通用户</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          class-name="status-col"
          label="操作"
          width="330"
        >
          <template slot-scope="{ row, $index }">
            <!--{{row.iUserLevel}}-->
            <el-row>
              <!--超管按钮-->
              <div v-if="roleId==0">
                <el-button
                  size="mini"
                  class="light_blue_btn"
                  @click="editCommunityPerson(row, $index)"
                >修改
                </el-button>
                <!-- 防止超管删除自己-->
                <el-popconfirm
                  v-if="row.iUserLevel==1||row.iUserLevel==2"
                  cancel-button-text="不用了"
                  class="m-margin-l10"
                  confirm-button-text="好的"
                  icon="el-icon-info"
                  icon-color="red"
                  title="您确定删除当前人员吗？"
                  @confirm="doDeleteCommunityPerson"
                >
                  <el-button
                    v-if="row.iUserLevel != 0"
                    slot="reference"
                    size="mini"
                    class="light_red_btn"
                    @click="deleteCommunityPerson(row)"
                  >删除
                  </el-button>
                </el-popconfirm>
              </div>
              <!-- 管理员-->
              <div v-if="roleId==1">
                <el-button
                  v-if="row.iUserLevel == '2'||userName==row.sUserName"
                  size="mini"
                  class="light_blue_btn"
                  @click="editCommunityPerson(row, $index)"
                >修改
                </el-button>
                <el-popconfirm
                  v-if="row.iUserLevel==2"
                  cancel-button-text="不用了"
                  class="m-margin-l10"
                  confirm-button-text="好的"
                  icon="el-icon-info"
                  icon-color="red"
                  title="您确定删除当前人员吗？"
                  @confirm="doDeleteCommunityPerson"
                >
                  <el-button
                    v-if="row.iUserLevel != 0"
                    slot="reference"
                    size="mini"
                    class="light_red_btn"
                    @click="deleteCommunityPerson(row)"
                  >删除
                  </el-button>
                </el-popconfirm>

              </div>
              <!-- 普通用户-->
              <div v-if="roleId==2">
                <el-button
                  v-if="userName==row.sUserName"
                  size="mini"
                  class="light_blue_btn"
                  @click="editCommunityPerson(row, $index)"
                >修改
                </el-button>
              </div>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <div class="tipsBox">
        <div>说明：</div>
        <div>超级管理员（最多1个）：具有所有权限；</div>
        <div>
          管理员（最多2个）：具有查看数据、数据导入和导出等权限，但是不能设置和保存；
        </div>
        <div>普通用户（最多5个）；权限只能查看数据，不能操作和导入导出</div>
      </div>
      <div style="margin-top: 20px">
        <el-button type="primary" @click="submitUiForm">修改UI密码</el-button>
      </div>
    </div>

    <el-dialog
      :title="title"
      v-if="dialogFormVisible"
      :visible.sync="dialogFormVisible"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户名" prop="newUserName">
              <el-input
                v-model.trim="form.newUserName"
                :disabled="form.id > -1"
                maxlength="1024"
                placeholder="请输入用户名"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户类型" prop="iUserLevel">
              <el-select v-model="form.iUserLevel" placeholder="请选择用户类型" v-if="form.iUserLevel!=0">
                <el-option
                  :label="item.label"
                  v-for="item in sexOptions"
                  :value="item.value"
                  :key="item.value"
                />
              </el-select>
              <el-input v-else placeholder="超级管理员" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="操作用户密码" prop="sPassword">
              <el-input
                id="sPassword"
                v-model.trim="form.sPassword"
                type="password"
                placeholder="请输入当前操作用户密码"
                maxlength="32"
                show-password
                @paste.native.capture.prevent="handleFalse"
                @copy.native.capture.prevent="handleFalse"
                @cut.native.capture.prevent="handleFalse"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!--         <el-row v-if="false">
          <el-col :span="24">
            <el-form-item label="权限">
              <el-select v-model="form.iUserLevel" placeholder="请选择">
                <el-option
                  v-for="(v, i) in sexOptions"
                  :key="i"
                  :label="v.label"
                  :value="v.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="24">
            <el-form-item :label="title=='添加用户'?'密码':`修改密码`" prop="newPassword">
              <el-input
                id="newPassword"
                v-model.trim="form.newPassword"
                maxlength="32"
                placeholder="请输入密码"
                type="password"
                show-password
                @paste.native.capture.prevent="handleFalse"
                @copy.native.capture.prevent="handleFalse"
                @cut.native.capture.prevent="handleFalse"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="确认密码" prop="secondNewPw">
              <el-input
                id="secondNewPw"
                v-model.trim="form.secondNewPw"
                placeholder="请确认密码"
                maxlength="32"
                type="password"
                show-password
                @paste.native.capture.prevent="handleFalse"
                @copy.native.capture.prevent="handleFalse"
                @cut.native.capture.prevent="handleFalse"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="registerLoading"
        >确 定
        </el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改UI密码" :visible.sync="uiDialogVisible" width="30%">
      <el-form ref="uiForm" :model="uiForm" label-width="80px">
        <el-form-item
          label="UI密码"
          prop="sPassword"
          :rules="uiPassWordRules"
        >
          <el-input
            placeholder="请输入密码"
            v-model="uiForm.sPassword"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="uiDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUIPW('uiForm')"
        >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import {
  getSystemUserListApi,
  addSystemUserApi,
  delSystemUserApi,
  editSystemUserApi,
  getSystemUserApi,
} from "@/api/access/equipment";
import {
  getUiPasswordApi,
  editUiPasswordApi,
} from "@/api/community/communityPerson.js";
import {Base64} from "js-base64";
import {mapGetters, mapMutations} from "vuex";
import {regPassword} from "@/utils/validate";
import {getPassWordCheckRegx} from "@/api/intelligent";
import Cookies from "js-cookie";

export default {
  components: {Pagination},
  props: {},
  data() {
    var checkUserPassword = (rule, value, callback) => {
      if (!value) {
        // console.log(this.passwordObj);
        return callback(new Error('密码不能为空'));
      }
      setTimeout(() => {
        if (!new RegExp(this.passwordObj.userPasswordRegex).test(value)) {
          console.log('in-test', this.passwordObj.userPasswordErrorMessage)
          callback(new Error(this.passwordObj.userPasswordErrorMessage));
        }
      }, 500)
    };
    var checkUIPassword = (rule, value, callback) => {
      if (!value) {
        console.log(this.passwordObj);
        return callback(new Error('密码不能为空'));
      }
      setTimeout(() => {
        if (!new RegExp(this.passwordObj.uiPasswordRegex).test(value)) {
          console.log('in-test')
          callback(new Error(this.passwordObj.userPasswordErrorMessage));
        }
      }, 500)
    };
    var validatePass2 = (rule, value, callback) => {
      // console.log(value,this.form.sPassword)
      if (value === "") {
        callback(new Error("请再次输入密码"));
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      rowObj:{},
      tableLoading:false,
      passwordObj: {},
      uiPassWordRules: [
        { required: true, message: '请输入UI密码', trigger: 'blur' },
        {
          required: true,
          pattern: /^[a-zA-Z0-9`~!@#$%^&*()-_+=|{}:;'".]{5,32}$/,
          message: '5-32位, 包含数字、大小写字母和英文符号',
          trigger: ['blur', 'change'],
        },
      ],
      list: [],
      total: 0,
      selectList: [],
      requestList: [],
      dialogFormVisible: false,
      form: {
        iUserLevel: 1,
        newPassword: "",
        newUserName: "",
        sPassword: "",
        sUserName: "admin",
        secondNewPw: "",
      },
      rules: {
        newUserName: [
          {required: true, trigger: "blur", message: "请输入用户名"},
        ],
        sPassword: [
          {required: true, trigger: "blur", message: "请输入密码"},
          {
            pattern: /^[a-zA-Z0-9`~!@#$%^&*()-_+=|{}:;'".]{5,32}$/,
            message: '5-32位, 包含数字、大小写字母和英文符号',
            trigger: ['blur', 'change'],
          },
        ],
        // newPassword: [
        //   {
        //     validator: checkUserPassword,
        //     trigger: "blur",
        //   },
        // ],
        newPassword: [
          {required: true, trigger: "blur", message: "请输入密码"},
          {
            pattern: /^[a-zA-Z0-9`~!@#$%^&*()-_+=|{}:;'".]{5,32}$/,
            message: '5-32位, 包含数字、大小写字母和英文符号',
            trigger: ['blur', 'change'],
          },
        ],
        // secondNewPw: [
        //   {
        //     validator: checkUserPassword,
        //     trigger: "blur",
        //   },
        // ],
        secondNewPw: [
          {
            required: true,
            message: "确认密码不能为空",
            trigger: ["change", "blur"],
          },
          {
            required: true,
            validator: validatePass2,
            trigger: ["change", "blur"],
          },
        ],
      },
      title: "",
      sexOptions: [
        // {label: "超级管理员", value: 0},
        {label: "管理员", value: 1},
        {label: "普通用户", value: 2},
      ],
      registerLoading: false,
      delForm: {},
      uiDialogVisible: false,
      uiForm: {
        sPassword: "",
      },
    };
  },
  created() {
    this.getList();
    this.getUiPassword();
    this.getRegx();
  },
  methods: {
    getRegx() {
      getPassWordCheckRegx().then(res => {
        this.passwordObj = {...res}
      })
    },
    // 禁止复制，剪切，拷贝
    handleFalse() {
      return;
    },
    // getSystemUser() {
    //   getSystemUserApi().then((res) => {
    //     console.log(res);
    //   });
    // },
    addUser() {
      this.title = "添加用户";
      this.dialogFormVisible = true;
      this.form = {
        iUserLevel: 1,
        newPassword: "",
        newUserName: "",
        sPassword: "",
        sUserName: "admin",
        secondNewPw: "",
        id: -1,
      };
    },
    submitForm() {
      let userlv1 = 0, userlv2 = 0;
      self = this;
      for (const i in this.list) {
        if (self.list[i].iUserLevel == 1) {
          userlv1++;
        }
        if (self.list[i].iUserLevel == 2) {
          userlv2++;
        }
      }
      if(this.title != '修改用户'){
        if (this.form.iUserLevel == 1) {
          userlv1++;
        } else if (this.form.iUserLevel == 2) {
          userlv2++;
        }
      }else{
        if(this.form.iUserLevel != this.rowObj.iUserLevel){
          if (this.form.iUserLevel == 1) {
            userlv1++;
          } else if (this.form.iUserLevel == 2) {
            userlv2++;
          }
        }
      }
      
      if (userlv1 > 2 || userlv2 > 5) {
        this.$message.error("用户数量已到上限");
        return false;
      }
      this.$refs.form.validate((valid) => {
        console.log(222)
        console.log(this.form);
        if (valid) {
          console.log('if-valid', this.form)
          let params = {...this.form};
          params.sPassword = Base64.encode(this.form.sPassword);
          params.newPassword = Base64.encode(this.form.newPassword);
          if (this.form.secondNewPw) {
            params.newPassword = Base64.encode(this.form.secondNewPw);
          }
          params.secondNewPw = Base64.encode(this.form.secondNewPw);
          this.registerLoading = true;
          let comApi;
          if (this.form.id == -1) {
            comApi = addSystemUserApi;
          } else {
            comApi = editSystemUserApi;
          }
          comApi(params)
            .then((res) => {
              this.resetForm("form");
              this.getList();
              this.dialogFormVisible = false;
              this.registerLoading = false;
              if (this.title != '修改用户'){
                this.$message.success("添加成功");
              } else {
                this.$message.success("修改成功");
              }
            })
            .catch((err) => {
              this.registerLoading = false;
            });
        }
      });
    },
    cancel() {
      this.resetForm("form");
      this.dialogFormVisible = false;
    },
    getList() {
      this.tableLoading = true
      getSystemUserApi().then((res) => {
        this.list = res;
        this.tableLoading = false
      });
    },
    editCommunityPerson(_row, _index) {
      this.title = "修改用户";
      this.dialogFormVisible = true;
      let newObj = this.$fn.deepCopy(_row);
      this.rowObj = newObj
      this.form.newUserName = newObj.sUserName;
      this.form.iUserLevel = newObj.iUserLevel;
      this.form.id = newObj.id;
    },
    deleteCommunityPerson(_row) {
      // console.log(_row);
      let newObj = this.$fn.deepCopy(_row);
      this.delForm.newUserName = newObj.sUserName;
      this.delForm.sUserName = "admin";
      this.delForm.sPassword = "admin";
      this.delForm.iUserLevel = newObj.iUserLevel;
    },
    doDeleteCommunityPerson() {
      this.delForm.sPassword = Base64.encode(this.delForm.sPassword);
      delSystemUserApi(this.delForm)
        .then((res) => {
          this.$message.success("删除成功");
          this.getList();
        })
        .catch((err) => {
          this.$message.success("删除成功");
        });
    },
    getUiPassword() {
      getUiPasswordApi().then((res) => {
        // console.log(res);
        this.uiForm.sLastChangeTime = res.sLastChangeTime;
        this.uiForm.id = res.id;
      });
    },
    submitUiForm() {
      this.uiDialogVisible = true;
      this.uiForm.sPassword = "";
    },
    submitUIPW(formName) {
      let params = {...this.uiForm};
      params.Password = this.uiForm.sPassword;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          editUiPasswordApi(params).then((res) => {
            // console.log(res);
            this.$message.success("修改UI密码成功");
            this.uiDialogVisible = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  computed: {
    ...mapGetters(["roleId"]),
    userName() {
      return Cookies.get("face-username");
    },
  },
};
</script>

<style lang="scss" scoped>
.tipsBox {
}
</style>
